package com.hnec.dms.log.format;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;

import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

/**
 * 普通格式日志输出，扩展至logback, 增加自定义补充的参数。
 *
 * @author hidebug
 */
public class LogPatternLayout extends PatternLayout {

    private String logName;

    public String doLayout(ILoggingEvent event) {
        String logInfo = super.doLayout(event);

        StringBuilder sb = new StringBuilder(logInfo);
        String mdcInfo = parserAndCleanMDCInfo(event);
        if (!mdcInfo.isEmpty()) {
            sb.append("logName: " + logName);
            sb.append(CoreConstants.TAB);
            sb.append("logld: " + generatorUUID());
            sb.append(CoreConstants.TAB);
            sb.append("reqInfo: ");
            sb.append(mdcInfo);
            sb.append(CoreConstants.LINE_SEPARATOR);
        }

        return sb.toString();
    }

    // 解析补充数据，解析获取后删除
    private String parserAndCleanMDCInfo(ILoggingEvent event) {
        StringBuilder sb = new StringBuilder();

        Map<String, String> mdcMap = event.getMDCPropertyMap();
        if (mdcMap != null && !mdcMap.isEmpty()) {
            for (Entry<String, String> entry : mdcMap.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
        }

        return sb.toString();
    }

    public void setLogName(String logName) {
        this.logName = logName;
    }

    /**
     * 32 uuid生成方法，去掉字符间的-
     *
     * @return
     */
    // TODO MX_M 要和链路跟踪统一ID，目前是临时做法
    private String generatorUUID() {
        String uuid = UUID.randomUUID().toString().replace("-", "");

        return uuid;
    }
}
